package com.edushare.common.global;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import org.apache.cayenne.access.DataContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.Application;

import com.edushare.common.dao.ConfigPropertiesDAO;
import com.edushare.common.orm.CayenneORMInterface;
import com.edushare.common.vo.ConfigProperties;

/**
 * Singleton. Loads system level properties.
 * @author Naishe
 *
 */
public class SystemGlobals {
	
	private static Log log = LogFactory.getLog(SystemGlobals.class);
	private static SystemGlobals globals = null;
	private Properties props = null;
	private Application wicketApplication = null; // a handle to wicket application object.
	
	/**
	 * Static accessor
	 * @return a handle to singleton instance of the class.
	 * @throws IOException
	 */
	public static SystemGlobals getInstance(){
		if(globals==null){
			globals = new SystemGlobals();			
		}
		return globals;
	}
	
	/**
	 * private constructor
	 * @throws IOException 
	 */
	private SystemGlobals(){
		props = new Properties();
		
		try {
			//this should be one time thing, so creating new ORMInterface manually
			CayenneORMInterface ormInterface = new CayenneORMInterface();
			ormInterface.setDataContext(DataContext.createDataContext());
			List<ConfigProperties> propList = new ConfigPropertiesDAO(
					ormInterface).getAllProperties();
			for (ConfigProperties prop : propList) {
				props.setProperty(prop.getName(), prop.getValue());
			}
		} catch (Exception e) {
			//Ignore any exception here, to let app start smoothly
			log.fatal("CONFIG PROPERTIES COULD NOT BE LOADED!!!");
		}
	}
	
	public Properties getProperties(){
		return this.props;
	}
	
	public void resetSystemGlobals(){
		globals = null;
	}

	public void setWicketApplication(Application wicketApplication) {
		this.wicketApplication = wicketApplication;
	}

	public Application getWicketApplication() {
		return wicketApplication;
	}

	public String getConfigProperty(String configPropertyName){
		return this.props.getProperty(configPropertyName);
	}

}
